<?php


namespace App\Dao;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Task;
use Hyperf\Database\Model\Builder;

class TaskDao extends AbstractDao
{
    public function where(array $where): Builder
    {
        $builder = Task::query();
        foreach ($where as $key => $value) {
            switch ($key) {
                case 'cooperative_ids':
                    $builder->whereIn('cooperative_id', $value);
                    break;
                case 'employer_ids':
                    $builder->whereIn('employer_id', $value);
                    break;
                case 'keywords':
                    $builder = $this->whereKeyWords($builder, $value);
                    break;
                default:
                    if (is_array($value)) {
                        $builder->where($key, $value[0], $value[1]);
                    } else {
                        $builder->where($key, $value);
                    }
            }
        }
        return $builder;
    }

    public function whereKeyWords(Builder $builder, $value)
    {
        $builder->where(function ($query) use ($value) {
            $query->where('title', 'like', '%' . $value . '%');
            $query->orWhereHas('user', function ($query) use ($value) {
                $query->where('phone', $value);
                $query->orWhere('nickname', 'like', '%' . $value . '%');
            });
        });
        return $builder;
    }

    /**
     * @param array $where
     * @return Task
     */
    public function firstOrFail(array $where): Task
    {
        /** @var Task $task */
        $task = $this->first($where);
        if (!$task) {
            throw new BusinessException(ErrorCode::TASK_NOT_EXIST);
        }
        return $task;
    }
}